package com.cuijq.ms.clone.v3;

import java.util.HashMap;
import java.util.List;

/**
 * @Classname Demo
 * @Description TODO
 * @Date 2021/5/14 16:49
 * @Created by CuiJQ
 */
public class Demo {

  private HashMap<String, SearchWord> currentKeywords = new HashMap<>();
  private long lastUpdateTime = -1;

  public void refresh() {
    // 原型模式就这么简单，拷贝已有对象的数据，更新少量差值
    /**
     * 拷贝分为深拷贝 和 浅拷贝。
     * 浅拷贝 得到的数据 与原始对象 共享数据
     * 深拷贝 得到的数据 是完完全全独立的对象
     *
     * 目前这里是浅拷贝
     */
    HashMap<String, SearchWord> newKeywords = (HashMap) currentKeywords.clone();
    // 从数据库中取出更新时间>lastUpdateTime的数据，放入到newKeywords中
    List<SearchWord> toBeUpdatedSearchWords = getSearchWords(lastUpdateTime);
    long maxNewUpdatedTime = lastUpdateTime;
    for (SearchWord searchWord : toBeUpdatedSearchWords) {
      if (searchWord.getLastUpdateTime() > maxNewUpdatedTime) {
        maxNewUpdatedTime = searchWord.getLastUpdateTime();
      }
      if (newKeywords.containsKey(searchWord.getKeyword())) {
        SearchWord oldSearchWord = newKeywords.get(searchWord.getKeyword());
        oldSearchWord.setCount(searchWord.getCount());
        oldSearchWord.setLastUpdateTime(searchWord.getLastUpdateTime());
      } else {
        newKeywords.put(searchWord.getKeyword(), searchWord);
      }
    }
    lastUpdateTime = maxNewUpdatedTime;
    currentKeywords = newKeywords;
  }

  private List getSearchWords(long lastUpdateTime) {
    // TODO: 从数据库中取出更新时间>lastUpdateTime的数据
    return null;
  }
}
